# template_system.py
from moviepy.editor import *
from .video_effects import VideoEffects
from .advanced_transitions import TransitionEffects

class EducationalTemplate:
    """教育类视频模板"""
    def __init__(self):
        self.title_duration = 2
        self.content_duration = 5
        self.transition_duration = 1
        self.effects = VideoEffects()
    
    def apply(self, video_clip):
        """应用教育模板"""
        # 应用教育风格滤镜
        styled_clip = self.effects.apply_filter(video_clip, "cinematic")
        
        # 添加标题
        title_text = "教育视频"
        title = TextClip(title_text, fontsize=60, color='white', font='SimHei', bg_color='black')
        title = title.set_position(('center', 'top')).set_duration(styled_clip.duration).resize(width=styled_clip.w * 0.8)
        
        # 添加水印
        watermark = TextClip("教育频道", fontsize=20, color='white', font='SimHei')
        watermark = watermark.set_position(('right', 'bottom')).set_duration(styled_clip.duration)
        
        # 组合视频
        final_clip = CompositeVideoClip([styled_clip, title, watermark])
        return final_clip

class MarketingTemplate:
    """营销类视频模板"""
    def __init__(self):
        self.logo_position = ('left', 'top')
        self.cta_duration = 3
        self.animation_duration = 0.5
        self.effects = VideoEffects()
    
    def apply(self, video_clip):
        """应用营销模板"""
        # 应用营销风格滤镜
        styled_clip = self.effects.apply_filter(video_clip, "warm")
        
        # 添加品牌Logo
        logo_path = "assets/logo.png"
        if os.path.exists(logo_path):
            try:
                logo = ImageClip(logo_path).resize(height=100)
                logo = logo.set_position(self.logo_position).set_duration(video_clip.duration)
            except Exception as e:
                # 如果Logo加载失败，使用文字Logo
                logo = TextClip("品牌", fontsize=30, color='red', font='SimHei', bg_color='white')
                logo = logo.set_position(self.logo_position).set_duration(video_clip.duration)
        else:
            # 如果Logo文件不存在，使用文字Logo
            logo = TextClip("品牌", fontsize=30, color='red', font='SimHei', bg_color='white')
            logo = logo.set_position(self.logo_position).set_duration(video_clip.duration)
        
        # 添加营销文案
        cta_text = TextClip("立即购买！", fontsize=40, color='yellow', font='SimHei', bg_color='red')
        cta_text = cta_text.set_position(('center', 'bottom')).set_duration(self.cta_duration)
        cta_text = cta_text.set_start(video_clip.duration - self.cta_duration)
        
        # 组合视频
        final_clip = CompositeVideoClip([styled_clip, logo, cta_text])
        return final_clip

class StorytellingTemplate:
    """故事类视频模板"""
    def __init__(self):
        self.dramatic_effects = True
        self.mood_filters = True
        self.emotional_music = True
        self.effects = VideoEffects()
    
    def apply(self, video_clip):
        """应用故事模板"""
        # 应用故事风格滤镜
        styled_clip = self.effects.apply_filter(video_clip, "vintage")
        
        # 添加情绪化元素
        if self.dramatic_effects:
            # 添加粒子效果，如光点
            styled_clip = self.effects.add_particle_effect(styled_clip, "stars", density=20)
        
        # 添加故事标题
        title_text = "故事标题"
        title = TextClip(title_text, fontsize=50, color='white', font='SimHei')
        title = title.set_position('center').set_duration(min(3, styled_clip.duration))
        
        # 如果视频足够长，将标题放在开头
        if styled_clip.duration > 3:
            title = title.set_position('center')
            final_clip = CompositeVideoClip([styled_clip])
            # 添加标题淡入淡出效果
            title_with_effects = title.fadein(0.5).fadeout(0.5)
            # 在视频开始处添加标题
            final_clip_with_title = CompositeVideoClip([
                final_clip,
                title_with_effects.set_start(0)
            ])
            return final_clip_with_title
        else:
            return styled_clip

class VideoTemplate:
    def __init__(self):
        self.templates = {
            "educational": EducationalTemplate(),
            "marketing": MarketingTemplate(),
            "storytelling": StorytellingTemplate()
        }
        self.effects = VideoEffects()
        self.transitions = TransitionEffects()
    
    def apply_template(self, video_clip, template_name: str):
        """应用模板"""
        if template_name in self.templates:
            return self.templates[template_name].apply(video_clip)
        else:
            # 如果模板不存在，返回原始视频
            return video_clip
    
    def get_available_templates(self):
        """获取可用模板列表"""
        return list(self.templates.keys())
    
    def create_custom_template(self, name: str, template_obj):
        """创建自定义模板"""
        self.templates[name] = template_obj
    
    def apply_multiple_effects(self, video_clip, template_name: str, effects_list: list):
        """应用模板和额外效果"""
        # 先应用模板
        templated_clip = self.apply_template(video_clip, template_name)
        
        # 再应用额外效果
        for effect in effects_list:
            if effect == "motion_blur":
                templated_clip = self.effects.add_motion_blur(templated_clip)
            elif effect == "fade_in":
                templated_clip = templated_clip.fadein(1)
            elif effect == "fade_out":
                templated_clip = templated_clip.fadeout(1)
            elif effect == "brightness_up":
                templated_clip = self.effects.adjust_brightness(templated_clip, 1.2)
            elif effect == "contrast_up":
                templated_clip = self.effects.adjust_contrast(templated_clip, 1.2)
            elif effect == "saturation_up":
                templated_clip = self.effects.adjust_saturation(templated_clip, 1.2)
        
        return templated_clip
    
    def get_template_info(self, template_name: str):
        """获取模板信息"""
        if template_name in self.templates:
            template_class = self.templates[template_name].__class__.__name__
            return {
                "name": template_name,
                "class": template_class,
                "description": f"{template_class} for creating {template_name} style videos"
            }
        else:
            return None
